package cn.jbolt.ai.app.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.jbolt.ai.core.chain.config.AppConfigConstant;
import cn.jbolt.ai.app.dao.AiAppSessionMapper;
import cn.jbolt.ai.app.entity.AiAppSession;
import cn.jbolt.ai.app.service.AiAppConfigService;
import cn.jbolt.util.cache.CacheUtil;
import cn.jbolt.util.Pager;
import cn.jbolt.util.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.jbolt.ai.app.service.AiAppSessionService;
import com.fasterxml.jackson.databind.JsonNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AiAppSessionServiceImpl extends ServiceImpl<AiAppSessionMapper, AiAppSession> implements AiAppSessionService {
    private static final Logger logger = LoggerFactory.getLogger(AiAppSessionServiceImpl.class);

    @Autowired
    private AiAppConfigService aiAppConfigService;

    @Override
    @Transactional
    public Result add(AiAppSession appSession) {
        boolean save = this.save(appSession);
        if (save) {
            setCache(appSession, appSession.getId());
            //取出config
            JsonNode config = appSession.getConfig();
            //放到appConfig中
            if (config != null) {
                Result result = aiAppConfigService.add(AppConfigConstant.LINK_TYPE_SESSION, appSession.getId(), config);
                if (result.isError()) {
                    return result;
                }
            }
            return Result.success(appSession);
        }
        return Result.error("添加失败");
    }

    @Override
    @Transactional
    public Result delete(Long id) {
        if (this.removeById(id)) {
            CacheUtil.removeObject(CacheUtil.KEY_APP_SESSION + "_" + id);
            logger.info("缓存中session移除成功:{}_{}", CacheUtil.KEY_APP_SESSION, id);
            //移除session配套的config
            Result result = aiAppConfigService.deleteByLinkId(AppConfigConstant.LINK_TYPE_SESSION, id);
            return result;
        }
        return Result.error("删除失败");
    }

    @Override
    public Result deleteByAppId(Long appId) {
        QueryWrapper<AiAppSession> query = new QueryWrapper<AiAppSession>().eq("app_id", appId);
        List<AiAppSession> sessionList = this.list(query);
        if (sessionList != null&& sessionList.size() > 0){
            for (AiAppSession session : sessionList) {
                CacheUtil.removeObject(CacheUtil.KEY_APP_SESSION + "_" + session.getId());
                logger.info("缓存中session移除成功:{}_{}", CacheUtil.KEY_APP_SESSION, session.getId());
            }
            boolean remove = this.remove(query);
            if (!remove) {
                return Result.error("删除失败");
            }
        }
        return Result.success();
    }

    @Override
    public Result getSession(Long sessionId) {
        AiAppSession session = getCache(sessionId);
        if (session == null) {
            session = this.getById(sessionId);
        }
        if (session != null) {
            //处理对应的appConfig
            JsonNode config = aiAppConfigService.getConfig(AppConfigConstant.LINK_TYPE_SESSION, sessionId);
            if (config != null) {
                session.setConfig(config);
                setCache(session, session.getId());
            }
            return Result.success(session);
        } else {
            return Result.error("会话不存在");
        }
    }

    @Override
    public Result listByPage(Long startId, Integer pageSize, String keywords, Long appId) {
        QueryWrapper<AiAppSession> queryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotEmpty(keywords)) {
            queryWrapper.like("name", keywords);
        }
        if (startId != null) {
            queryWrapper.lt("id", startId);
        }
        if (appId != null) {
            queryWrapper.eq("app_id", appId);
        }
        queryWrapper.eq("is_debug", false);
        queryWrapper.orderByDesc("id");
        return Result.success(Pager.from(this.page(new Page<>(1, pageSize), queryWrapper)));
    }

    @Override
    public Result update(AiAppSession aiAppSession) {
        if (updateById(aiAppSession)) {
            setCache(aiAppSession, aiAppSession.getId());
            return Result.success(aiAppSession);
        } else {
            return Result.error("更新失败");
        }
    }


    /**
     * 从缓存中获取session
     *
     * @return
     */
    public AiAppSession getCache(Long sessionId) {
        AiAppSession cacheSession = CacheUtil.getObject(CacheUtil.KEY_APP_SESSION + "_" + sessionId);
        logger.info("缓存中取出session:{}_{}-----{}:", CacheUtil.KEY_APP_SESSION, sessionId, cacheSession);
        return cacheSession;
    }

    /**
     * 把session放入缓存
     *
     * @param session
     */
    public void setCache(AiAppSession session, Long sessionId) {
        CacheUtil.putObject(CacheUtil.KEY_APP_SESSION + "_" + sessionId, session, -1, null);
        logger.info("session存入缓存:{}_{},已放入缓存,无过期时间-----{}:", CacheUtil.KEY_APP_SESSION, sessionId, session);
    }
}
